package operation;

import JDBC.JDBCUtils;

import Medicine.Pharmacy;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.Map;
import java.util.Scanner;

public class BuyMedicine implements IOPeration{
    @Override
    public void work(Pharmacy pharmacy) throws SQLException {
        //创建QueryRunner对象
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        System.out.println("购买药品....");
        Scanner sc = new Scanner(System.in);

        System.out.println("请输入您需要的药品名称: ");
        String name = sc.nextLine();
        // 1. 先查询药品是否存在以及其Amount
        String query = "SELECT Amount FROM Medicine WHERE Name=?";
        int amount = 0;
        Map<String, Object> medicineMap = qr.query(query, new MapListHandler(), name).get(0); // 假设查询结果至少有一个元素
        if (medicineMap != null && medicineMap.containsKey("Amount")) {
            amount = (Integer) medicineMap.get("Amount");
        }

        if (amount > 0) {
            // 2. 如果存在，检查 Amount 是否足够
            System.out.println("有该药品，且库存充足");
            // 3. 提示用户输入购买数量
            System.out.println("请输入购买数量！");
            int num = sc.nextInt(); // 读取用户输入的购买数量

            // 检查用户输入的数量是否大于库存
            if (num > amount) {
                System.out.println("输入的数量超过了库存，"+name+"的库存仅剩 " + amount);
            } else {
                // 4. 使 Amount 数量减去用户输入的数量
                String updateSql = "UPDATE Medicine SET Amount=Amount-? WHERE Name=? AND Amount >= ?";
                Object[] updateParms = {num, name, num}; // 注意这里的参数顺序
                int count = qr.update(updateSql, updateParms);
                if (count < 1) {
                    System.out.println("购买药品失败！");
                } else {
                    // 有一个方法来获取当前登录用户的 帐号

                    String user = getCurrentUser();
                    // 更新 buyman 表中的 point
                    String updatePointsSql = "UPDATE buyman SET point=point+1 WHERE user=?";
                    qr.update(updatePointsSql, user);
                    System.out.println("购买药品成功！");
                    int point = getCurrentUserPoints(user, qr);
                    System.out.println("恭喜您获取积分！积分可以随时使用,当前积分为"+point);
                }
            }
        } else {
            System.out.println("很抱歉，您想购买的药品暂时库存不足");
        }
    }


    public static String getCurrentUser() {
        Scanner sc = new Scanner(System.in);
        System.out.println("确认您的用户账号");
        String user = sc.nextLine();
        return user;
    }
    private int getCurrentUserPoints(String user, QueryRunner qr) throws SQLException {
        String query = "SELECT point FROM buyman WHERE user=?";
        ScalarHandler<Integer> sh = new ScalarHandler<>();
        return qr.query(query, sh, user);
    }
}
